package login;

import student.Student;

import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;

public class LoginSystem {
    private HashMap<String, String> userDatabase; // 用户名和密码
    private HashMap<String, String> roleDatabase; // 用户名和角色

    public LoginSystem() {
        userDatabase = new HashMap<>();
        roleDatabase = new HashMap<>();

        // 初始化管理员账户
        userDatabase.put("admin", hashPassword("admin123")); // 预定义管理员账户
        roleDatabase.put("admin", "Admin");
    }

    // 注册普通用户
    public void registerUser(String username, String password) {
        if (userDatabase.containsKey(username)) {
            System.out.println("用户名已存在，请尝试其他用户名！");
        }else if(!usernameCheck(username)){
            System.out.println("用户名不符合格式要求！");
        }else if(!passwordCheck(password)){
            System.out.println("密码不符合格式要求！");
        }else {
            userDatabase.put(username, hashPassword(password));
            roleDatabase.put(username, "User"); // 默认角色为普通用户
            System.out.println("注册成功！用户名: " + username + "，角色: User");
        }
    }

    // 获取用户角色
    public String getRole(String username) {
        return roleDatabase.get(username);
    }

    // 用户登录
    public String login(String username, String password) {
        if (userDatabase.containsKey(username)) {
            String storedPasswordHash = userDatabase.get(username);//提取密码
            if (storedPasswordHash.equals(hashPassword(password))) {
                System.out.println("登录成功！欢迎 " + username + "！");
                return roleDatabase.get(username); // 返回用户角色
            } else {
                System.out.println("密码错误！");
            }
        } else {
            System.out.println("用户名不存在！");
        }
        return null; // 登录失败返回 null
    }

    // 密码加密（MD5 哈希）
    private String hashPassword(String password) {
        try {
            //获取 MD5 消息摘要算法的实例
            MessageDigest md = MessageDigest.getInstance("MD5");
            //将密码字符串转换为字节数组，并计算 MD5 哈希值
            byte[] digest = md.digest(password.getBytes());
            //将字节数组转换为十六进制字符串
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b));//转化位两位16进制
            }
            //返回十六进制表示的 MD5 哈希值
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            // 捕获异常，如果系统不支持 MD5 算法
            throw new RuntimeException("无法加密密码！");
        }
    }
    boolean passwordCheck(String password){
        return Pattern.matches("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[~@#$%*_\\-+=:.?])[A-Za-z0-9~@#$%*_\\-+=:.?]{6,16}$",password);
    }
    boolean usernameCheck(String username){
        return  Pattern.matches("^[0-9]{6,12}$",username);
    }
    // 保存到文件
    public void saveToFile() {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("userDatabase.dat"));
             ObjectOutputStream oos2 = new ObjectOutputStream(new FileOutputStream("roleDatabase.dat"))) {
            oos.writeObject(userDatabase);
            oos2.writeObject(roleDatabase);
            System.out.println("保存成功!");
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }

    // 从文件加载
    public void loadFromFile() {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("userDatabase.dat"));
             ObjectInputStream ois2 = new ObjectInputStream(new FileInputStream("roleDatabase.dat"))) {
            userDatabase = (HashMap<String, String>) ois.readObject();
            roleDatabase = (HashMap<String, String>) ois2.readObject();
            System.out.println("导出成功!");
        } catch (IOException | ClassNotFoundException e) {
            System.out.println("Error: " + e.getMessage());
        }
        /*使用try-with-resources语法自动关闭文件*/
    }
}
